package org.javaopenaccess.service.schema;

import java.io.File;
import java.util.GregorianCalendar;

import org.javaopenaccess.dao.schema.SchemaDao;
import org.javaopenaccess.dao.schema.SchemaSaveException;
import org.javaopenaccess.model.Db4oSchema;
import org.javaopenaccess.model.Schema;
import org.javaopenaccess.model.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.db4o.Db4o;
/**
 * This implementations is DB4o specific, 
 * for creating a database schema.
 * @author Miku
 *
 */
public class Db4oSchemaService implements SchemaService {
	
	private SchemaDao schemaDao;

	private String schemaStorage;
	private Logger logger = LoggerFactory.getLogger(this.getClass().getName());

	public static final String FILE_EXTENSION = ".db";
	
	@Override
	public Schema createSchema(String name, User user) throws SchemaAlreadyExistsException, SchemaException{
		//create folder if not existing
		String absoluteFilePath = schemaStorage + "/"+ user.getUserName() + "/" + name + FILE_EXTENSION;
		File folder = new File (schemaStorage + "/"+ user.getUserName());
		if (!folder.exists()){
			folder.mkdirs();
		}	
		File dbFile = new File (absoluteFilePath);		
		if (dbFile.exists()){
			logger.info("User trying to create schema with the same name");
			throw new SchemaAlreadyExistsException("Schema with this name for the current user already exists");
		}else{
			try {
				//create the schema by opening a file and closing it straight
				Db4o.openFile(absoluteFilePath).close();
				Schema schema = new Db4oSchema(new GregorianCalendar().getTimeInMillis(), name, user, absoluteFilePath);
				schemaDao.store(schema);
				return schema;
			} catch (SchemaSaveException e) {
				throw new SchemaException("Schema creation failed due to error in saving the new schema object to the database", e); 
			} catch (Exception e) {
				throw new SchemaException("Schema creation failed due to Db4o error. Please check properties and db settings", e); 
			}
			
		}
	}

	public void setSchemaStorage(String schemaStorage) {
		this.schemaStorage = schemaStorage;
	}
	
	public void setSchemaDao(SchemaDao schemaDao) {
		this.schemaDao = schemaDao;
	}

	@Override
	public Schema getSchema(String name) throws SchemaNotFoundException {
		return schemaDao.getSchema(name);
	}


}
